package image2

import (
	"bytes"
	"errors"
	"github.com/nfnt/resize"
	"image/jpeg"
)

type Buffer struct {
	Buf    []byte
	X      int
	Y      int
	Width  int
	Height int
}

func (b *Buffer) Process(canvas *Canvas) error {
	copyImg, err := jpeg.Decode(bytes.NewReader(b.Buf))
	if err != nil {
		return errors.New("读取微信code失败. " + err.Error())
	}
	if b.Width > 0 || b.Height > 0 {
		copyImg = resize.Resize(uint(b.Width), uint(b.Height), copyImg, resize.Lanczos3)
	} else {
		b.Width, b.Height = loadImageSize(copyImg)
	}

	var endX, endY = b.X + b.Width, b.Y + b.Height
	if endX > canvas.Width || endY > canvas.Height {
		return errors.New("数组越界！")
	}

	for x := b.X; x < endX; x++ {
		for y := b.Y; y < endY; y++ {
			if canvas.Placeholder[x][y] == 1 {
				continue
			}
			canvas.Placeholder[x][y] = 1
			canvas.Canvas.Set(x, y, copyImg.At(x-b.X, y-b.Y))
		}
	}
	return nil
}
